//提交验证码管理
package models

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var tokenRond *rand.Rand
var tokens map[string]int64
var tokenMutex sync.Mutex

func init() {
	tokenRond = rand.New(rand.NewSource(time.Now().UnixNano()))
	tokens = make(map[string]int64)
}

func GetToken() string {
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	now := time.Now().Unix()
	for {
		token := Strtomd5(fmt.Sprintf("%v%v", now, tokenRond.Intn(999999)))
		_, ok := tokens[token]
		if ok {
			continue
		}
		tokens[token] = now
		return token
	}
}

func CheckToken(token string) bool {
	if token == "" {
		return false
	}
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	_, ok := tokens[token]
	return ok
}

func DelToken(token string) {
	if token == "" {
		return
	}
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	_, ok := tokens[token]
	if ok {
		delete(tokens, token)
	}

	//超过10分钟就删除
	now := time.Now().Unix()
	for k, v := range tokens {
		if now-v >= 600 {
			delete(tokens, k)
		}
	}

	return
}
